import axios from "axios"
import EnvConfig from '@/config'

class NetWork {
    constructor(baseURL) {
        baseURL = baseURL || EnvConfig.baseURL
        // create an axios instance
        this.service = axios.create({
            baseURL, // url = base url + request url EnvConfig.baseURL
            withCredentials: true, // send cookies when cross-domain requests
            timeout: 5000, // request timeout
        })
        // 请求拦截器 request interceptor
        // this.service.interceptors.request.use(
        //     config => {
        //     // do something before request is sent
        //     }
        // )
        // 响应拦截器 response interceptor
        this.service.interceptors.response.use(
            config => {
                let res = config.data
                let headers = config.headers
                let reqConfig = config.config

                if (reqConfig.responseType === 'blob') {
                    return {
                        data: res,
                        type: headers['content-type']
                    }
                }

                if (res.code !== 200) {
                    return Promise.reject(res)
                }
                return res
            }, 
            error => {
                console.error(error)
                let errMsg = `${error}`
                if (errMsg.includes('timeout')) {
                    errMsg = '服务响应超时，请稍后重试'
                }
                return Promise.reject(errMsg)
            }
        )
    }

    post(url, parameter, config = {}) {
        return this.service.post(url, parameter, config)
    }

    get(url, parameter) {
        return this.service.get(url, {
            params: parameter
        })
    }

    download(url, parameter, config = {}) {
        return this.service.post(url, parameter, {
            ...config,
            responseType: 'blob'
        })
    }

    upload(url, parameter, config = {}) {
        return this.service.post(url, parameter, {
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            ...config
        })
    }
}

export default new NetWork()
